package com.backoffice.util {

import flash.display.DisplayObject;

import flash.events.Event;
import flash.events.EventDispatcher;

import mx.controls.Alert;
import mx.events.ModuleEvent;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;

public class ExtModuleManger extends EventDispatcher {

        private var module: IModuleInfo;
        private var _mDisplayObject: DisplayObject;

        public static const UNLOAD_MODULE_EVENT: String = "moduleisunloaded";
        public static const LOAD_MODULE_EVENT: String = "moduleisloaded";

        public function loadModule(path: String, preload: Boolean = false): void {
            module = ModuleManager.getModule(path);
            if(!preload) {
                module.addEventListener(ModuleEvent.READY, modEventHandler);
            } else {
                module.addEventListener(ModuleEvent.READY, modPreloadEventHandler);
            }
            module.addEventListener(ModuleEvent.ERROR, modErrorEventHandler);
            module.load();
        }

        private function modEventHandler(e: ModuleEvent): void {
            _mDisplayObject = module.factory.create() as DisplayObject;
            this.dispatchEvent(new Event(LOAD_MODULE_EVENT));
        }

         private function modPreloadEventHandler(e: ModuleEvent): void {
            //TODO
        }

         private function modErrorEventHandler(e: ModuleEvent): void {
            Alert.show("There was an error loading the module.");
         }

        public function unloadModule(): void {
            module.addEventListener(ModuleEvent.UNLOAD, modUnloadEventHandler);
            module.unload();
        }

        private function modUnloadEventHandler(e: ModuleEvent): void {
            this.dispatchEvent(new Event(UNLOAD_MODULE_EVENT));
        }

        public function get mDisplayObject(): DisplayObject {
            return _mDisplayObject;
        }
    }

}